const Joi = require('joi');

/**
 * User validation schemas for API V1
 * Legacy validation with basic rules for backward compatibility
 * @deprecated Use V2 validation instead
 */

// V1 User creation schema - simplified for legacy support
const userCreateSchemaV1 = Joi.object({
  username: Joi.string()
    .min(3)
    .max(30)
    .required()
    .messages({
      'string.min': 'Username must be at least 3 characters long',
      'string.max': 'Username cannot exceed 30 characters',
      'any.required': 'Username is required'
    }),
    
  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': 'Please provide a valid email address',
      'any.required': 'Email is required'
    }),
    
  password: Joi.string()
    .min(6)
    .required()
    .messages({
      'string.min': 'Password must be at least 6 characters long',
      'any.required': 'Password is required'
    }),
    
  role: Joi.string()
    .valid('user', 'admin')
    .default('user')
    .messages({
      'any.only': 'Role must be either user or admin'
    })
});

// V1 User update schema - basic validation
const userUpdateSchemaV1 = Joi.object({
  username: Joi.string()
    .min(3)
    .max(30)
    .messages({
      'string.min': 'Username must be at least 3 characters long',
      'string.max': 'Username cannot exceed 30 characters'
    }),
    
  email: Joi.string()
    .email()
    .messages({
      'string.email': 'Please provide a valid email address'
    }),
    
  role: Joi.string()
    .valid('user', 'admin')
    .messages({
      'any.only': 'Role must be either user or admin'
    })
}).min(1).messages({
  'object.min': 'At least one field must be provided for update'
});

/**
 * Validation middleware for V1 user creation
 * @deprecated Use V2 validation for new implementations
 */
const validateUser = (req, res, next) => {
  const { error, value } = userCreateSchemaV1.validate(req.body, { 
    abortEarly: false 
  });

  if (error) {
    const errors = error.details.map(detail => detail.message);

    // V1 legacy error format
    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors
    });
  }

  req.body = value;
  next();
};

/**
 * Validation middleware for V1 user updates
 * @deprecated Use V2 validation for new implementations
 */
const validateUserUpdate = (req, res, next) => {
  const { error, value } = userUpdateSchemaV1.validate(req.body, { 
    abortEarly: false 
  });

  if (error) {
    const errors = error.details.map(detail => detail.message);

    // V1 legacy error format
    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors
    });
  }

  req.body = value;
  next();
};

module.exports = {
  validateUser,
  validateUserUpdate,
  userCreateSchemaV1,
  userUpdateSchemaV1
};